using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using AutoBase.Shared;
using AutoBase.BusinessObjects;

public partial class SearchResults : System.Web.UI.UserControl
{
    #region Public Properties

    /// <summary>
    /// Maximum number of visible vehicles records per page, default value is 10
    /// </summary>
    public int MaxVehiclesPerPage
    {
        get
        {
            object o = this.ViewState["_MaxVehiclesPerPage"];
            if (o == null)
                return 10; // default to 10
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_MaxVehiclesPerPage"] = value;
        }
    }

    /// <summary>
    /// Number of records returned by the search query 
    /// </summary>
    public int Rows
    {
        get
        {
            object o = this.ViewState["_ReturnRows"];
            if (o == null)
                return -1; // default to 10
            else
                return (int)o;
        }
    }

    public string HostName
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_HostName"];
            if (o == null)
            {
                return string.Empty; // default page index of 0
            }
            else
                return (string)o;
        }

        set
        {
            this.ViewState["_HostName"] = value;
        }
    }

    /// <summary>
    /// Search By branch id
    /// </summary>
    public int BranchId
    {
        get
        {
            object o = this.ViewState["_BranchId"];
            if (o == null)
                return -1;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_BranchId"] = value;
        }
    }

    /// <summary>
    /// Search by company Id
    /// </summary>
    public int CompanyId
    {
        get
        {
            object o = this.ViewState["_CompanyId"];
            if (o == null)
                return 0;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CompanyId"] = value;
        }
    }

    /// <summary>
    /// List of branches and corresponding localtion names, seperated by a '|' (bar) 
    /// Ex: 1574~MoorhouseAv|1573~Carman Rd|2204~Trade-In House
    /// </summary>
    public string BranchIdLocationList
    {
        get
        {
            object o = this.ViewState["_BranchIdLocationList"];
            if (o == null)
                return string.Empty;
            else
                return (string)o;
        }
        set
        {
            this.ViewState["_BranchIdLocationList"] = value;
        }
    }

    /// <summary>
    /// Category List seperated by a '|' (bar) 
    /// Ex 1: 2
    /// Ex 2: 2|4|5
    /// </summary>
    public string CategoryList
    {
        get
        {
            object o = this.ViewState["_CategoryList"];
            if (o == null)
                return string.Empty;
            else
                return (string)o;
        }
        set
        {
            this.ViewState["_CategoryList"] = value;
        }
    }

    public bool IsPriceVisible
    {
        get
        {
            object o = this.ViewState["_IsPriceVisible"];
            if (o == null)
                return true;
            else
                return (bool)o;
        }
        set
        {
            this.ViewState["_IsPriceVisible"] = value;
        }
    }

    public int ManufacturerId
    {
        get
        {
            object o = this.ViewState["_ManufacturerId"];
            if (o == null)
                return -1;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_ManufacturerId"] = value;
        }
    }

    public int ModelId
    {
        get
        {
            object o = this.ViewState["_ModelId"];
            if (o == null)
                return -1;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_ModelId"] = value;
        }
    }

    /// <summary>
    /// Year range
    /// Ex 1: 2001|2005
    /// Ex 2: 0|2005
    /// Ex 3: 2001|0
    /// </summary>
    public string YearRange
    {
        get
        {
            object o = this.ViewState["_YearRange"];
            if (o == null)
                return string.Empty;
            else
                return (string)o;
        }
        set
        {
            this.ViewState["_YearRange"] = value;
        }
    }

    /// <summary>
    /// Year range
    /// Ex 1: 0|20000
    /// Ex 2: 5000|12000
    /// Ex 3: 15000|0
    /// Ex 4: 15,000|22,300 
    /// </summary>
    public string PriceRange
    {
        get
        {
            object o = this.ViewState["_PriceRange"];
            if (o == null)
                return string.Empty; // default to 10
            else
                return (string)o;
        }
        set
        {
            this.ViewState["_PriceRange"] = value;
        }
    }

    /// <summary>
    /// Customer code to futher filter result
    /// </summary>
    public string CustomizedFilterCode
    {
        get
        {
            object o = this.ViewState["_CustomizedFilterCode"];
            if (o == null)
                return string.Empty; // 
            else
                return (string)o;
        }
        set
        {
            this.ViewState["_CustomizedFilterCode"] = value;
        }
    }

    #endregion Public Properties

    private PagedDataSource dataSearchResults = new PagedDataSource();

    enum ViewType
    {
        List = 0,
        Gallery = 1,
        GalleryList = 2,
        GalleryListLarge = 3,
    }

    #region Private Properties

    private int CurrentPage
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0; // default page index of 0
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    private string LastStyle
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_LastStyle"];
            if (o == null)
                return string.Empty; // default page index of 0
            else
                return (string)o;
        }

        set
        {
            this.ViewState["_LastStyle"] = value;
        }
    }

    //ImageNoneUrl
    private string ImageNoneUrl
    {
        get
        {
            // look for current page in ViewState
            object o = this.ViewState["_ImageNoneUrl"];
            if (o == null)
                return "images/imageunavailable"; // default page index of 0
            else
                return (string)o;
        }

        set
        {
            this.ViewState["_ImageNoneUrl"] = value;
        }
    }

    #endregion Private Properties

    protected void Page_Load(object sender, EventArgs e)
    {
        LoadData();
    }

    public void LoadData()
    {
        VehicleSearchManger.WriteLine(this.ID.ToString(), "Loading Data...");
        if (!Page.IsPostBack)
        {
            LoadControlData();
            VehicleSearchManger.WriteLine(this.ID.ToString(), "Loading Control Data...Successful!");
        }
        uicPageSelect.Items.Clear();
        LoadSearchResults();
        VehicleSearchManger.WriteLine(this.ID.ToString(), "Loading Data...Successful!");
    }

    private void LoadControlData()
    {
        //load sort order drop down
        uicOrder.Items.Clear();
        uicOrder.Items.Add(new ListItem("Asc", "asc"));
        uicOrder.Items.Add(new ListItem("Desc", "desc"));

        // Order by
        uicSortBy.Items.Clear();
        uicSortBy.Items.Add(new ListItem("Make/Model", "1"));
        uicSortBy.Items.Add(new ListItem("Year", "2"));
        uicSortBy.Items.Add(new ListItem("Type", "3"));

        int categoryId = 0;
        if (CategoryList.Length == 1)
        {
            int.TryParse(CategoryList, out categoryId);
        }
        if (categoryId == (int)VehicleFunctions.VehicleCategories.Boat)
        {
            uicSortBy.Items.Add(new ListItem("Length", "9"));
        }
        else
        {
            uicSortBy.Items.Add(new ListItem("CCs", "4"));
            uicSortBy.Items.Add(new ListItem("Odometer", "5"));
        }
        uicSortBy.Items.Add(new ListItem("Price", "7"));
        uicSortBy.Items.Add(new ListItem("Recently Added", "10"));

        //Views
        uicViews.Items.Clear();
        uicViews.Items.Add(new ListItem("List", ((int)ViewType.List).ToString()));
        uicViews.Items.Add(new ListItem("Gallery", ((int)ViewType.Gallery).ToString()));
        uicViews.Items.Add(new ListItem("Gallery List", ((int)ViewType.GalleryList).ToString()));
        uicViews.Items.Add(new ListItem("Gallery List Large", ((int)ViewType.GalleryListLarge).ToString()));

        uicOrder.SelectedIndex = 0;
        uicSortBy.SelectedIndex = 0;
        uicViews.SelectedIndex = 1;
    }

    private void LoadSearchResults()
    {
        string temp = string.Empty;
        ViewVehiclesRetailCollection vehicleRetail = new ViewVehiclesRetailCollection();

        dataSearchResults.DataSource = null;
        dataSearchResults.AllowPaging = true;
        dataSearchResults.PageSize = MaxVehiclesPerPage;
        vehicleRetail = PrepairQuery(vehicleRetail);
        vehicleRetail.Query.es.Top = 1000;

        dataSearchResults.DataSource = vehicleRetail;

        // Load page numbers to the Page drop down box
        if (uicPageSelect.Items.Count == 0)
        {
            uicPageSelect.Items.Clear();
            if (dataSearchResults.PageCount > 1)
            {
                for (int j = 0; j < dataSearchResults.PageCount; j++)
                {
                    uicPageSelect.Items.Add(new ListItem((j + 1).ToString(), j.ToString()));
                }
                uicPageSelect.SelectedIndex = CurrentPage;
            }
            if (CurrentPage >= dataSearchResults.PageCount)
            {
                CurrentPage = dataSearchResults.PageCount - 1;
            }
            if (CurrentPage < 0)
            {
                CurrentPage = 0;
            }
        }

        //Move the record bookmark to the proper page number
        dataSearchResults.CurrentPageIndex = CurrentPage;
        divStockList.Visible = true;

        //Handle FunctionBar
        uicLinkPrevious.Visible = !dataSearchResults.IsFirstPage;
        uicLinkNext.Visible = !dataSearchResults.IsLastPage;
        uicLinkLast.Visible = !dataSearchResults.IsLastPage;
        uicLinkFirst.Visible = !dataSearchResults.IsFirstPage;

        //Footer links
        uicLinkPrevious_Botom.Visible = !dataSearchResults.IsFirstPage;
        uicLinkNext_Botom.Visible = !dataSearchResults.IsLastPage;
        uicLinkLast_Botom.Visible = !dataSearchResults.IsLastPage;
        uicLinkFirst_Botom.Visible = !dataSearchResults.IsFirstPage;

        if (dataSearchResults.PageCount > 1)
        {
            divFunctionBarTop.Visible = true;
            divFunctionBarBotttom.Visible = true;
            uicFunctionBarTopNotice.Visible = false;
            uicFunctionBarBotttomNotice.Visible = false;
            uicPageNotice.InnerHtml = "of " + dataSearchResults.PageCount.ToString() + " pages of results.";
        }
        else
        {
            divFunctionBarTop.Visible = false;
            divFunctionBarBotttom.Visible = false;
            uicFunctionBarTopNotice.Visible = true;
            uicFunctionBarBotttomNotice.Visible = true;

            //uicNotice.Text = string.Empty;
            switch (dataSearchResults.Count)
            {
                case 0:
                    //show message to user
                    //uicNotice.Text = "No Records Found.";
                    divStockList.Visible = false;
                    break;
                case 1:
                    uicFunctionBarTopNotice.Text = "1 Record Found.";
                    break;

                default:
                    uicFunctionBarTopNotice.Text = dataSearchResults.Count.ToString() + " Records Found.";
                    uicFunctionBarBotttomNotice.Text = dataSearchResults.Count.ToString() + " Records Found.";
                    break;
            }
        }

        this.ViewState["_ReturnRows"] = dataSearchResults.Count;

        //bind data
        uicDataListGallery.Visible = false;
        uicRepeaterList.Visible = false;
        uicRepeaterGalleryList.Visible = false;

        if (uicViews.SelectedIndex == (int)ViewType.Gallery)
        {
            uicDataListGallery.Visible = true;
            uicDataListGallery.DataSource = dataSearchResults;
            uicDataListGallery.DataBind();
        }
        else if (uicViews.SelectedIndex == (int)ViewType.GalleryList)
        {
            uicRepeaterGalleryList.Visible = true;
            uicRepeaterGalleryList.DataSource = dataSearchResults;
            uicRepeaterGalleryList.DataBind();
        }
        else if (uicViews.SelectedIndex == (int)ViewType.GalleryListLarge)
        {
            uicRepeaterGalleryList.Visible = true;
            uicRepeaterGalleryList.DataSource = dataSearchResults;
            uicRepeaterGalleryList.DataBind();
        }
        else if (uicViews.SelectedIndex == (int)ViewType.List)
        {
            uicRepeaterList.Visible = true;
            uicRepeaterList.DataSource = dataSearchResults;
            uicRepeaterList.DataBind();
        }
    }

    /// <summary>
    /// Build the query and load data
    /// </summary>
    /// <param name="vehicles"></param>
    /// <returns></returns>
    private ViewVehiclesRetailCollection PrepairQuery(ViewVehiclesRetailCollection vehicles)
    {

        short shortValFrom = -1;
        short shortValTo = -1;
        decimal decimalValFrom = -1;
        decimal decimalValTo = -1;
        System.Collections.ArrayList arrayWhereQuery = new System.Collections.ArrayList();
        System.Collections.ArrayList objectIdList = new System.Collections.ArrayList();
        char[] charsToTrim = { ',' };

        HiddenField uicConstructUrl = new HiddenField();
        uicConstructUrl.Value = string.Empty;

        #region Query

        #region Customized Filters
        switch (CustomizedFilterCode)
        {
            case "104":
                arrayWhereQuery.Add(vehicles.Query.ModelDetail.Like("%Triple S%"));
                break;

            case "demo":
                arrayWhereQuery.Add(vehicles.Query.ModelDetail.Like("%DEMO%"));
                break;

            case "signature":
                arrayWhereQuery.Add(vehicles.Query.ModelDetail.Like("%signature%"));
                break;

            case "nonsignature":
                arrayWhereQuery.Add(vehicles.Query.ModelDetail.NotLike("%signature%"));
                break;

            case "bmw3":
                ManufacturerId = 9;
                arrayWhereQuery.Add(vehicles.Query.ModelName.Like("3%"));
                break;

            case "bmw7":
                ManufacturerId = 9;
                arrayWhereQuery.Add(vehicles.Query.ModelName.Like("7%"));
                break;

            case "bmwx5":
                ManufacturerId = 9;
                arrayWhereQuery.Add(vehicles.Query.ModelName.Like("X5%"));
                break;

            case "bmwz3":
                ManufacturerId = 9;
                arrayWhereQuery.Add(vehicles.Query.ModelName.Like("Z3%"));
                break;

            case "under10k":
                PriceRange = "0|10000";
                break;

            case "newonly":
                arrayWhereQuery.Add(vehicles.Query.IsNew.Equal(true));
                break;

            case "usedonly":
                arrayWhereQuery.Add(vehicles.Query.IsNew.Equal(false));
                break;

            case "specials":
                arrayWhereQuery.Add(vehicles.Query.IsSpecial.Equal(true));
                break;

            case "ssyng":
                ManufacturerId = 78;
                break;
            default:
                break;
        }

        #endregion

        int objectId = 0;
        if (BranchIdLocationList.Length > 0 && BranchIdLocationList.Split('|').Length > 0)
        {
            foreach (string id in BranchIdLocationList.Split('|'))
            {
                if (id.Split('~').Length > 0)
                {
                    int.TryParse(id.Split('~')[0], out objectId);
                }
                else
                {
                    int.TryParse(id, out objectId);
                }
                if (objectId > 0)
                {
                    objectIdList.Add(objectId);
                }
            }
            if (objectIdList.Count > 0)
            {
                arrayWhereQuery.Add(vehicles.Query.BranchId.In(objectIdList.ToArray()));
            }
        }
        else if (CompanyId > 0)
        {
            arrayWhereQuery.Add(vehicles.Query.CompanyId.Equal(CompanyId));
        }
        else if (BranchId > 0)
        {
            arrayWhereQuery.Add(vehicles.Query.BranchId.Equal(BranchId));

        }


        //Category List 
        objectIdList = new System.Collections.ArrayList();
        objectId = 0;
        if (CategoryList.Length > 0)
        {
            if (CategoryList.Split('|').Length > 0)
            {
                foreach (string id in CategoryList.Split('|'))
                {
                    if (id.Split('~').Length > 0)
                    {
                        int.TryParse(id.Split('~')[0], out objectId);
                    }
                    else
                    {
                        int.TryParse(id, out objectId);
                    }
                    if (objectId > 0)
                    {
                        objectIdList.Add(objectId);
                    }
                }
                if (objectIdList.Count > 0)
                {
                    arrayWhereQuery.Add(vehicles.Query.CategoryId.In(objectIdList.ToArray()));
                }
            }
            else
            {
                if (int.TryParse(CategoryList, out objectId))
                {
                    arrayWhereQuery.Add(vehicles.Query.CategoryId.Equal(CategoryList));
                }
            }
        }

        //Year
        shortValFrom = -1;
        shortValTo = -1;
        if (YearRange.Length > 0 && YearRange.Split('|').Length > 1)
        {
            if (YearRange.Split('|')[0].Length > 0)
            {
                short.TryParse(YearRange.Split('|')[0], out shortValFrom);
            }
            if (YearRange.Split('|')[1].Length > 0)
            {
                short.TryParse(YearRange.Split('|')[1], out shortValTo);
            }
            if (shortValFrom > 0 && shortValTo > 0)
            {
                arrayWhereQuery.Add(vehicles.Query.Year.Between(shortValFrom, shortValTo));
            }
            else
            {
                if (shortValFrom > 0)
                {
                    arrayWhereQuery.Add(vehicles.Query.Year.GreaterThanOrEqual(shortValFrom));
                }
                if (shortValTo > 0)
                {
                    arrayWhereQuery.Add(vehicles.Query.Year.LessThanOrEqual(shortValTo));
                }
            }
        }

        //Price
        decimalValFrom = -1;
        decimalValTo = -1;

        if (PriceRange.Length > 0 && PriceRange.Split('|').Length > 1)
        {
            if (PriceRange.Split('|')[0].Length > 0)
            {
                decimal.TryParse(PriceRange.Split('|')[0], out decimalValFrom);
            }
            if (YearRange.Split('|')[1].Length > 0)
            {
                decimal.TryParse(PriceRange.Split('|')[1], out decimalValTo);
            }
            if (decimalValFrom > 0 && decimalValTo > 0)
            {
                arrayWhereQuery.Add(vehicles.Query.RetailPrice.Between(decimalValFrom, decimalValTo));
            }
            else
            {
                if (decimalValFrom > 0)
                {
                    arrayWhereQuery.Add(vehicles.Query.RetailPrice.GreaterThanOrEqual(decimalValFrom));
                }
                if (decimalValTo > 0)
                {
                    arrayWhereQuery.Add(vehicles.Query.RetailPrice.LessThanOrEqual(decimalValTo));
                }
            }
        }

        //Manufactuere
        if (ManufacturerId > 0)
        {
            arrayWhereQuery.Add(vehicles.Query.ManufacturerId.Equal(ManufacturerId));
        }

        //Model
        if (ModelId > 0)
        {
            arrayWhereQuery.Add(vehicles.Query.ModelId.Equal(ModelId));
        }

        #endregion Query

        # region SortBy

        EntitySpaces.Interfaces.esOrderByDirection orderBy = EntitySpaces.Interfaces.esOrderByDirection.Ascending;
        string sortBy = "-1";

        if (uicOrder.SelectedIndex > 0)
        {
            orderBy = uicOrder.SelectedItem.Value == "desc" ? EntitySpaces.Interfaces.esOrderByDirection.Descending : EntitySpaces.Interfaces.esOrderByDirection.Ascending;
        }
        if (uicSortBy.SelectedIndex > 0)
        {
            sortBy = uicSortBy.SelectedItem.Value;
        }
        switch (sortBy)
        {
            case "1":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Year, orderBy);
                break;

            case "2":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Year, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "3":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.VehicleTypeName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "4":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.CcRating, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "5":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Odometer, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "6":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ExtColour, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "7":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.RetailPrice, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "8":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Transmission, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "9":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Length, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            case "10":
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Id, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                break;

            default:
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ManufacturerName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelName, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.ModelDetail, orderBy);
                vehicles.Query.OrderBy(ViewVehiclesMetadata.ColumnNames.Year, orderBy);
                break;
        }
        # endregion

        if (arrayWhereQuery.Count > 0)
        {
            vehicles.Query.Where(arrayWhereQuery.ToArray());
            // Load data
            vehicles.Query.Load();
#if (DEBUG)
                System.Diagnostics.Debug.WriteLine(vehicles.Query.es.LastQuery);
#endif
        }
        return vehicles;

    }

    #region EVENTS

    protected void LinkButton_Click(Object sender, CommandEventArgs e)
    {
        switch (e.CommandName.ToLower())
        {
            case "next":
                CurrentPage += 1;
                uicPageSelect.SelectedIndex = CurrentPage;
                LoadSearchResults();
                break;

            case "first":
                CurrentPage = 0;
                uicPageSelect.SelectedIndex = CurrentPage;
                LoadSearchResults();
                break;

            case "prev":
                CurrentPage -= 1;
                uicPageSelect.SelectedIndex = CurrentPage;
                LoadSearchResults();
                break;

            case "last":
                CurrentPage = uicPageSelect.Items.Count - 1;
                uicPageSelect.SelectedIndex = CurrentPage;
                LoadSearchResults();
                break;

            default:
                break;
        }
    }

    protected void DropDownListSelectedIndexChanged(object sender, EventArgs e)
    {
        string newUrl = string.Empty;
        switch (((DropDownList)sender).ID)
        {
            case "uicPageSelect":
                CurrentPage = Convert.ToInt32(((DropDownList)sender).SelectedValue);
                break;

            case "uicSortBy":
                if (uicSortBy.SelectedItem.Value.Equals("10"))
                {
                    uicOrder.SelectedIndex = 1;
                }
                break;

            case "uicSortOrder":
                break;
        }
        LoadSearchResults();

    }

    protected void uicDataList_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        VehicleFunctions vehicleFunctions = new VehicleFunctions();
        ViewVehiclesRetail vehicle = new ViewVehiclesRetail();

        string temp = string.Empty;
        string imageLocator = string.Empty;
        string imageUrl = string.Empty;
        string imageNonUrl = string.Empty;
        int intVal = 0;

        if (e.Item.ItemType == ListItemType.Item ||
            e.Item.ItemType == ListItemType.AlternatingItem)
        {
            vehicle = (ViewVehiclesRetail)e.Item.DataItem;
            if (sender is DataList)
            {
                if (((DataList)sender).ID.Equals("uicDataListGallery"))
                {
                    goto Label_ListGallery;
                }
            }
        }

    Label_ListGallery:
        #region Gallery

        #region Set Styles
        HtmlTableRow divItem = new HtmlTableRow();
        if (e.Item.FindControl("divDataListItem") != null)
        {
            divItem = (HtmlTableRow)e.Item.FindControl("divDataListItem");
        }
        else if (e.Item.FindControl("divDataListAlternatItem") != null)
        {
            divItem = (HtmlTableRow)e.Item.FindControl("divDataListAlternatItem");
        }
        System.Math.DivRem(e.Item.ItemIndex, 2, out intVal);
        if (intVal == 0)
        {
            if (divItem != null)
            {
                if (LastStyle.Length == 0)
                {
                    divItem.Attributes.Add("class", "stock_item");
                    LastStyle = "stock_item";
                }
                else if (LastStyle.Equals("stock_item"))
                {
                    divItem.Attributes.Add("class", "stock_item_alternate");
                    LastStyle = "stock_item_alternate";
                }
                else
                {
                    divItem.Attributes.Add("class", "stock_item");
                    LastStyle = "stock_item";
                }
            }
        }
        else
        {
            if (divItem != null)
            {
                if (LastStyle.Length == 0)
                {
                    divItem.Attributes.Add("class", "stock_item");
                }
                else
                {
                    divItem.Attributes.Add("class", LastStyle);
                }
            }
        }

        #endregion Set Styles

        #region Set Data
        if (e.Item.FindControl("uicVehicleImage") != null)
        {
            //imageNonUrl = HostName + ImageNoneUrl + (e.Item.ItemType == ListItemType.Item ? "1.png" : "2.png");
            imageNonUrl = HostName + ImageNoneUrl + "2.png";

            if (vehicle.ImageCount.Value > 0)
            {
                imageLocator = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.AbsolutePath);
                imageUrl = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath);

                ((Image)e.Item.FindControl("uicVehicleImage")).AlternateText = "Stock No: " + vehicle.StockNumber;
                if (System.IO.File.Exists(imageLocator)) //for file exists to work u need a physical path like "F:/Autobase/img/123765_0.jpg"
                {
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageUrl;
                }
                else
                {
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageNonUrl;
                }
#if (DEBUG)
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageUrl;
#endif
            }
            else
            {
                ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageNonUrl;
            }
        }

        temp = string.Empty;
        if (e.Item.FindControl("uicVehicleHeder") != null)
        {
            temp = vehicle.Year.ToString() + "&nbsp;" + vehicle.ManufacturerModel
                + "&nbsp;" + vehicle.ModelDetail;
            ((HtmlGenericControl)e.Item.FindControl("uicVehicleHeder")).InnerHtml = temp;
        }

        int objectId = 0;
        string branchLocation = string.Empty;
        if (BranchIdLocationList.Length > 0 && BranchIdLocationList.Split('|').Length > 0)
        {
            foreach (string id in BranchIdLocationList.Split('|'))
            {
                if (id.Split('~').Length > 1)
                {
                    if (int.TryParse(id.Split('~')[0], out objectId))
                    {
                        if (vehicle.BranchId == objectId && id.Split('~')[1] != null)
                        {
                            branchLocation = id.Split('~')[1];
                        }
                    }
                }
            }
        }

        temp = string.Empty;
        if (branchLocation.Length > 0)
        {
            temp += vehicle.VehicleTypeName + "&nbsp;" + string.Format("{0:#,#}", vehicle.Odometer) + "kms" + "<br/>";
            temp += string.Format("{0:#,#}", vehicle.CcRating) + "cc&nbsp;" + vehicle.Transmission + "<br/>";
            if (IsPriceVisible)
            {
                temp += "$" + string.Format("{0:#,#}", vehicle.RetailPrice);
                temp += " - [" + branchLocation + "] <br/>";
            }
            else
            {
                temp += "[" + branchLocation + "] <br/>";
            }
        }
        else
        {
            temp += vehicle.VehicleTypeName + "&nbsp;" + string.Format("{0:#,#}", vehicle.Odometer) + "kms" + "<br/>";
            temp += string.Format("{0:#,#}", vehicle.CcRating) + "cc&nbsp;" + vehicle.Transmission + "<br/>";
            if (IsPriceVisible)
            {
                temp += "$" + string.Format("{0:#,#}", vehicle.RetailPrice) + "<br/>";
            }
        }
        if (e.Item.FindControl("uicVehicleDescription") != null)
        {
            ((HtmlGenericControl)e.Item.FindControl("uicVehicleDescription")).InnerHtml = temp;
        }

        if (e.Item.FindControl("divDataListItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
                "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");


        }
        else if (e.Item.FindControl("divDataListAlternatItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
                "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");

        }
        //altItem.Attributes.Add("onclick", "javascript:window.location='" + SystemSetting.UrlPublicSite + "vehicle/VehicleDetails.aspx?ID=" + vehicleId + "'");

        #endregion Set Data

        return; // To skip the next commands
        #endregion Gallery
    }

    protected void uicRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        VehicleFunctions vehicleFunctions = new VehicleFunctions();
        ViewVehiclesRetail vehicle = new ViewVehiclesRetail();

        string temp = string.Empty;
        string imageLocator = string.Empty;
        string imageUrl = string.Empty;
        string imageNonUrl = string.Empty;

        if (e.Item.ItemType == ListItemType.Item ||
            e.Item.ItemType == ListItemType.AlternatingItem)
        {
            vehicle = (ViewVehiclesRetail)e.Item.DataItem;
            if (sender is Repeater)
            {
                if (((Repeater)sender).ID.Equals("uicRepeaterList"))
                {
                    goto Label_List;
                }
                if (((Repeater)sender).ID.Equals("uicRepeaterGalleryList"))
                {
                    goto Label_ListGallery;
                }
            }
            return;
        }
        else if (e.Item.ItemType == ListItemType.Header)
        {
            if (!IsPriceVisible)
            {
                if (e.Item.FindControl("uicPrice") != null)
                {
                    ((HtmlTableCell)e.Item.FindControl("uicPrice")).Visible = false;
                }
            }
        }

    Label_List:
        #region List
        temp = string.Empty;
        if (e.Item.FindControl("uicStockNo") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicStockNo")).InnerHtml = vehicle.StockNumber;
        }
        if (e.Item.FindControl("uicMakeModel") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicMakeModel")).InnerHtml = vehicle.ManufacturerModel;
        }
        if (e.Item.FindControl("uicYear") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicYear")).InnerHtml = vehicle.Year.ToString();
        }
        if (e.Item.FindControl("uicType") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicType")).InnerHtml = vehicle.VehicleTypeName;
        }
        if (e.Item.FindControl("uicTransmission") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicTransmission")).InnerHtml = vehicle.Transmission;
        }
        if (e.Item.FindControl("uicCC") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicCC")).InnerHtml = string.Format("{0:#,#}", vehicle.CcRating);
        }
        if (e.Item.FindControl("uicOdometer") != null)
        {
            ((HtmlTableCell)e.Item.FindControl("uicOdometer")).InnerHtml = string.Format("{0:#,#}", vehicle.Odometer);
        }

        if (e.Item.FindControl("uicPrice") != null)
        {
            if (!IsPriceVisible)
            {
                if (e.Item.FindControl("uicPrice") != null)
                {
                    ((HtmlTableCell)e.Item.FindControl("uicPrice")).Visible = false;
                }
            }
            else
            {
                if (vehicle.RetailPrice > 0)
                {
                    ((HtmlTableCell)e.Item.FindControl("uicPrice")).InnerHtml = "$" + string.Format("{0:#,#}", vehicle.RetailPrice);
                }
            }
        }
        if (e.Item.FindControl("divDataListItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
                "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");
        }
        else if (e.Item.FindControl("divDataListAlternatItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
                "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");

        }
        return;
        #endregion List

    Label_ListGallery:
        #region List Gallery
        if (e.Item.FindControl("uicVehicleImage") != null)
        {

            //imageNonUrl = HostName + ImageNoneUrl + (e.Item.ItemType == ListItemType.Item ? "1.png" : "2.png");
            imageNonUrl = HostName + ImageNoneUrl + "2.png";

            if (vehicle.ImageCount > 0)
            {
                if (uicViews.SelectedIndex == (int)ViewType.GalleryList)
                {
                    imageLocator = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.AbsolutePath);
                    imageUrl = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Thumb, FileFunctions.FilePathType.HttpFullPath);
                }
                else if (uicViews.SelectedIndex == (int)ViewType.GalleryListLarge)
                {
                    imageLocator = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Medium, FileFunctions.FilePathType.AbsolutePath);
                    imageUrl = vehicleFunctions.GetVehicleImagePath(vehicle.Id.Value, 1, VehicleFunctions.VehicleImageSize.Medium, FileFunctions.FilePathType.HttpFullPath);
                }
                ((Image)e.Item.FindControl("uicVehicleImage")).AlternateText = "Stock No: " + vehicle.StockNumber;
                if (System.IO.File.Exists(imageLocator)) //for file exists to work u need a physical path like "F:/Autobase/img/123765_0.jpg"
                {
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageUrl;
                }
                else
                {
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageNonUrl;
                }
#if (DEBUG)
                    ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageUrl;
#endif
            }
            else
            {
                ((Image)e.Item.FindControl("uicVehicleImage")).ImageUrl = imageNonUrl;
            }
        }

        //uicVehicleHeder" runat="
        //="uicVehicleDescription"
        temp = string.Empty;
        if (e.Item.FindControl("uicVehicleHeder") != null)
        {
            temp = vehicle.Year.ToString() + "&nbsp;" + vehicle.ManufacturerModel + "&nbsp;" + vehicle.ModelDetail;
            ((HtmlGenericControl)e.Item.FindControl("uicVehicleHeder")).InnerHtml = temp;
        }

        int objectId = 0;
        string branchLocation = string.Empty;
        if (BranchIdLocationList.Length > 0 && BranchIdLocationList.Split('|').Length > 0)
        {
            foreach (string id in BranchIdLocationList.Split('|'))
            {
                if (id.Split('~').Length > 1)
                {
                    if (int.TryParse(id.Split('~')[0], out objectId))
                    {
                        if (vehicle.BranchId == objectId && id.Split('~')[1] != null)
                        {
                            branchLocation = id.Split('~')[1];
                        }
                    }
                }
            }
        }

        temp = string.Empty;
        if (branchLocation.Length > 0)
        {
            temp += vehicle.VehicleTypeName + "&nbsp;" + string.Format("{0:#,#}", vehicle.Odometer) + "kms" + "<br/>";
            temp += string.Format("{0:#,#}", vehicle.CcRating) + "cc&nbsp;" + vehicle.Transmission + "<br/>";
            temp += " - [" + branchLocation + "] <br/>";
        }
        else
        {
            temp += vehicle.VehicleTypeName + "&nbsp;" + string.Format("{0:#,#}", vehicle.Odometer) + "kms" + "<br/>";
            temp += string.Format("{0:#,#}", vehicle.CcRating) + "cc&nbsp;" + vehicle.Transmission + "<br/>";
        }
        if (e.Item.FindControl("uicVehicleDescription") != null)
        {
            ((HtmlGenericControl)e.Item.FindControl("uicVehicleDescription")).InnerHtml = temp;
        }

        if (IsPriceVisible)
        {
            if (e.Item.FindControl("uicPrice") != null && vehicle.RetailPrice > 0)
            {
                ((HtmlGenericControl)e.Item.FindControl("uicPrice")).InnerHtml = "$" + string.Format("{0:#,#}", vehicle.RetailPrice);
            }
        }

        if (e.Item.FindControl("divDataListItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListItem")).Attributes.Add("onclick",
                    "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");
        }
        else if (e.Item.FindControl("divDataListAlternatItem") != null)
        {
            //((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
            //    "javascript:window.location='" + HostName + "VehicleDetails.aspx?id=" + vehicle.Id.Value.ToString() + "'");
            ((HtmlTableRow)e.Item.FindControl("divDataListAlternatItem")).Attributes.Add("onclick",
                "javascript:window.location='" + HostName + System.IO.Path.GetFileName(Request.PhysicalPath) + "?id=" + vehicle.Id.Value.ToString() + "'");

        }
        //altItem.Attributes.Add("onclick", "javascript:window.location='" + SystemSetting.UrlPublicSite + "vehicle/VehicleDetails.aspx?ID=" + vehicleId + "'");
        return;
        #endregion List Gallery
    }

    #endregion


}
